<?php

namespace plugin\ycMassage\app\api\controller;

use app\common\manager\SettingsMgr;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\model\MassageUserDealer;
use plugin\ycMassage\app\model\MassageUserDealerLog;
use plugin\ycMassage\app\model\MassageUserFinanceAccount;
use plugin\ycMassage\utils\Rsa;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use GuzzleHttp\Client;
use plugin\ycMassage\app\model\MassageUserWallet;
use plugin\ycMassage\utils\Str;
use plugin\ycMassage\utils\WechatHelper;
use support\Request;
use support\Response;
use think\facade\Env;

class DealerController extends BaseController
{
    protected $noNeedLogin = ['dealerQrcode'];
    protected $noNeedAppid = ['dealerQrcode'];
    public function people(Request $request)
    {
        $limit = $request->get('limit', 20);
        $where = [];
        $where[] = ['a.dealer_uid', '=', $request->uid];
        $where[] = ['a.saas_appid', '=', $request->saas_appid];
        $Data  = MassageUser::alias('a')->where($where)
            ->join('massage_user_technician b', 'a.id=b.uid', 'left')
            ->order('a.id desc')->field('a.nickname,a.headimg,a.mobile,a.state,a.create_time,b.uid as technician_id')
            ->paginate($limit)->each(function ($item) {
            })
            ->toArray();
        return parent::successRes($Data);
    }
    public function dealer(Request $request)
    {
        $UserDealer = MassageUserDealer::where(['uid' => $request->uid])->find();
        $people_num = 0;
        $order_num = 0;
        $order_price = 0;
        $MassageUserWallet = MassageUserWallet::where(['uid' => $request->uid])->find();
        if ($UserDealer) {
            $people_num = $UserDealer->people_num;
            $order_num = $UserDealer->order_num;
            $order_price = $UserDealer->order_price;
        }
        $dealer_price = $MassageUserWallet->dealer_money_sum;
        $withdrawal_price = $MassageUserWallet->dealer_money;
        $domain = getHpConfig('domain', (int)$request->saas_appid, 'plugins_domains');
        $config = getHpConfig('', $request->saas_appid, 'dealer');
        $data = [
            'state' => $UserDealer ? $UserDealer->state : null,
            'UserFinanceAccount' => [
                'alipay' => MassageUserFinanceAccount::where(['uid' => $request->uid, 'channels' => 'alipay'])->field('qrcode,name,mobile')->find(),
                'wxpay' => MassageUserFinanceAccount::where(['uid' => $request->uid, 'channels' => 'wxpay'])->field('qrcode,name,mobile')->find(),
            ],
            'user' => [
                'people_num' => $people_num,
                'order_num' => $order_num,
                'order_price' => $order_price,
                'price' => $dealer_price,
                'withdrawal_price' => $withdrawal_price,
            ],
            'link' => $this->getDealerLink($request),
            'qrcode' => "{$domain}/{$this->pluginPrefix}/api/Dealer/dealerQrcode?uid={$request->uid}&saas_appid={$request->saas_appid}",
            'config' => $config
        ];
        return parent::successRes($data);
    }
    private function getDealerLink(Request $request)
    {
        $domain = getHpConfig('domain', (int)$request->saas_appid, 'plugins_domains');
        return $domain . "/app/ycMassage/#/?appid={$request->saas_appid}&dealer_uid={$request->uid}";
    }
    public function dealerQrcode(Request $request, $isPoster = false)
    {
        if(!$request->uid){
            $request->uid = (int)$request->get('uid');
            $request->saas_appid = (int)$request->get('saas_appid');
        }
        $platform = $request->get('platform');
        $applet = SettingsMgr::group($request->saas_appid, 'applet');
        if ($platform == 'MP-WEIXIN' && !empty($applet['applet_appid']) && !empty($applet['applet_secret'])) {
            $mpqrcodePath = public_path("uploads/ycMassage/mpqrcode");
            $env_version = 'release';
            if (Env::get('APP_MODE') == 'dev') {
                $env_version = 'trial';
            }
            $mpqrcode = $mpqrcodePath . "{$request->saas_appid}_{$request->uid}_{$env_version}.jpeg";
            if (file_exists($mpqrcode)) {
                if ($isPoster) {
                    return $mpqrcode;
                }
                return Response::create(file_get_contents($mpqrcode))->contentType('image/jpeg');
            }
            $access_token = (new WechatHelper)->getMPAccessToken($request->saas_appid);
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
            $data = [
                'scene' => "dealer_uid={$request->uid}",
                'page' => 'pages/index/index',
                'check_path' => false,
                'width' => 400,
                'auto_color' => false,
                'env_version' => $env_version,
                'line_color' => ['r' => 0, 'g' => 0, 'b' => 0],
            ];
            $client = new Client();
            $response = $client->post($url, ['json' => $data]);
            $result = $response->getBody()->getContents();
            if (substr($result, 0, 1) == '{') {
                $result = json_decode($result, true);
                if (isset($result['errcode'])) {
                    return parent::fail("[{$result['errcode']}]" . $result['errmsg']);
                }
            }
            # 判断$mpqrcode目录是否存在
            if (!is_dir($mpqrcodePath)) {
                mkdir($mpqrcodePath, 0777, true);
            }
            file_put_contents($mpqrcode, $result);
            if ($isPoster) {
                return $mpqrcode;
            }
            return Response::create($result)->contentType('image/jpeg');
        }
        $builder = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data($this->getDealerLink($request))
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(400)
            ->margin(10)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
            ->validateResult(false);
        $result = $builder->build();
        if ($isPoster) {
            $qrcodePath = public_path("uploads/ycMassage/dealerQrcode");
            if (!is_dir($qrcodePath)) {
                mkdir($qrcodePath, 0777, true);
            }
            $qrcode = $qrcodePath . "{$request->saas_appid}_{$request->uid}.png";
            $result->saveToFile($qrcode);
            return $qrcode;
        }
        return Response::create($result->getString())->contentType('image/png');
    }
    public function applyDealer(Request $request)
    {
        $state = getHpConfig('state', $request->saas_appid, 'dealer');
        if ($state != 'yes') {
            return parent::fail('分销功能未开启');
        }
        $UserDealer = MassageUserDealer::where(['uid' => $request->uid])->find();
        if ($UserDealer) {
            return parent::fail('已经申请过了');
        }
        $apply_price = (float) getHpConfig('apply_price', $request->saas_appid, 'dealer');
        if ($apply_price > 0) {
            return $this->json('需要支付', 60000);
        }
        $UserDealer = new MassageUserDealer();
        $UserDealer->uid = $request->uid;
        $UserDealer->saas_appid = $request->saas_appid;
        $apply = getHpConfig('apply', $request->saas_appid, 'dealer');
        if ($apply == 'no') {
            $UserDealer->state = 1;
        } else {
            $UserDealer->state = 0;
        }
        $UserDealer->save();
        return parent::success('申请成功');
    }
    public function dealerLog(Request $request)
    {
        $limit = $request->get('limit', 20);
        $where = [];
        $where[] = ['uid', '=', $request->uid];
        $where[] = ['saas_appid', '=', $request->saas_appid];
        $Data  = MassageUserDealerLog::where($where)->with(['fromUser', 'order'])->order('id desc')
            ->paginate($limit)
            ->each(function ($item) {
                switch ($item->level) {
                    case 1:
                        $item->level_text = '直推';
                        break;
                    case 2:
                        $item->level_text = '间推';
                        break;
                    case 3:
                        $item->level_text = '三级';
                        break;
                }
            })
            ->toArray();
        return parent::successRes($Data);
    }
    public function getPoster(Request $request)
    {
        $domain = getHpConfig('domain', (int)$request->saas_appid, 'plugins_domains');
        $data = [];
        $posterBg = root_path("plugin/ycMassage/public/image") . 'user_poster.png';
        try {
            $qrcode = $this->dealerQrcode($request, true);
        } catch (\Throwable $th) {
            return $this->fail($th->getMessage());
        }
        $data = [
            'poster' => $domain . '/' . $this->composePoster($request, $posterBg, $qrcode),
            'link' => $this->getDealerLink($request),
        ];
        return $this->successRes($data);
    }
    public function composePoster($request, $posterBg, $qrcode)
    {
        $image = imagecreatefrompng($posterBg);
        $width = imagesx($image);
        $height = imagesy($image);
        $system = getHpConfig('', $request->saas_appid, 'system');
        if (!empty($system['web_name'])) {
            list($r, $g, $b) = sscanf('#13374D', "#%02x%02x%02x");
            $color = imagecolorallocate($image, $r, $g, $b);
            $font = root_path("plugin/ycMassage/public/image") . 'PingFangSCMedium.ttf';
            imagettftext($image, 24, 0, 52, $height - 54, $color, $font, "诚邀加入 {$system['web_name']}");
            $data['web_name'] = $system['web_name'];
        }
        # 判断$qrcode是png还是jpeg
        if (Str::endsWith($qrcode, '.png')) {
            $qrcode = imagecreatefrompng($qrcode);
        } else {
            $qrcode = imagecreatefromjpeg($qrcode);
        }
        $qrcodeWidth = imagesx($qrcode);
        $qrcodeHeight = imagesy($qrcode);
        $targetSize = 150;
        $resizedOverlayImage = imagecreatetruecolor($targetSize, $targetSize);
        // 保持透明度（针对PNG图像）
        imagealphablending($resizedOverlayImage, false);
        imagesavealpha($resizedOverlayImage, true);

        // 使用 imagecopyresampled() 将叠加图片缩放到目标尺寸
        imagecopyresampled($resizedOverlayImage, $qrcode, 0, 0, 0, 0, $targetSize, $targetSize, $qrcodeWidth, $qrcodeHeight);
        imagedestroy($qrcode);

        imagecopy($image, $resizedOverlayImage, $width - $targetSize - 40, $height - $targetSize - 20, 0, 0, $targetSize, $targetSize);
        imagedestroy($resizedOverlayImage);
        # 转base64
        ob_start();
        imagepng($image);
        $image_data = ob_get_contents();
        ob_end_clean();
        imagedestroy($image);
        $imagePath = "uploads/ycMassage/dealerPoster";
        $imagePublicPath = public_path($imagePath);
        if (!is_dir($imagePublicPath)) {
            mkdir($imagePublicPath, 0777, true);
        }
        $imageFile = "{$request->saas_appid}_{$request->uid}.png";
        $imageUrl = $imagePublicPath . $imageFile;
        if (file_exists($imageUrl)) {
            @unlink($imageUrl);
        }
        file_put_contents($imageUrl, $image_data);
        return $imagePath . '/' . $imageFile;
    }
}
